<template>
  <div class="attachment-list">
    <!-- {{ normalizedEmployeeResignFileVoList }} -->
    <div
      v-for="(file, index) in normalizedEmployeeResignFileVoList"
      class="attachment-item"
    >
      <div class="file-info">
        <el-icon class="file-icon">
          <component
            :is="isNotArray ? getFileIcon(file) : getFileIcon(file.file)"
          />
        </el-icon>

        <span class="file-name">{{
          isNotArray ? getFileName(file) : getFileName(file.file)
        }}</span>
      </div>

      <div class="file-actions">
        <el-link
          type="primary"
          :underline="false"
          :href="`${props.baseUrl}${file}`"
          style="font-size: 12px"
        >
          预览
        </el-link>
        <el-divider direction="vertical" />
        <!-- 只有当父组件传递了 showDeleteBtn 且其值为 true 时才显示删除按钮 -->
        <el-link
          v-if="showDeleteBtn"
          type="primary"
          :underline="false"
          @click="handleDelete(index)"
          style="font-size: 12px"
        >
          删除
        </el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import {
  Document,
  Picture,
  VideoPlay,
  Files,
  Delete,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps({
  employeeResignFileVoList: {
    type: Array,
    default: () => [],
  },
  baseUrl: {
    type: String,
    default: import.meta.env.VITE_APP_BASE_API,
  },
  showDeleteBtn: {
    type: Boolean,
    default: false, // 默认不显示删除按钮
  },
});

const emit = defineEmits(["delete", "update:employeeResignFileVoList"]);

// 预览相关状态
const previewUrl = ref("");
const previewType = ref("");
const isNotArray = ref(false); // 用于判断是否不是数组

// 获取文件显示名称
// const getFileName = (filePath) => {
//   return filePath?.split("/").pop() || "未命名文件";
// };

// 获取文件显示名称（安全版本）
const getFileName = (file) => {
  try {
    // 处理多种输入类型
    const path =
      typeof file === "string"
        ? file
        : file?.url || file?.name || file?.fileName || "";

    // 提取文件名逻辑
    if (!path) return "未命名文件";

    // 处理URL和普通路径
    const lastSegment = path.split(/[\\/]/).pop();
    const cleanName = lastSegment.split("?")[0]; // 去除URL参数
    return cleanName || "未命名文件";
  } catch (e) {
    console.error("获取文件名出错:", e);
    return "无效文件";
  }
};

// 获取文件类型图标
// const getFileIcon = (filePath) => {
//   const ext = filePath?.split(".").pop()?.toLowerCase();
//   const iconMap = {
//     png: Picture,
//     jpg: Picture,
//     jpeg: Picture,
//     gif: Picture,
//     doc: Document,
//     xdoc: Document,
//     pdf: Files,
//     xls: Document,
//     xlsx: Document,
//     mp4: VideoPlay,
//     avi: VideoPlay,
//     txt: VideoPlay,
//   };
//   return iconMap[ext] || Files;
// };
// 获取文件类型图标（基于文件名）
const getFileIcon = (filePath) => {
  // 确保 filePath 是字符串
  if (typeof filePath !== "string") {
    // console.error("filePath is not a string:", filePath);
    return Files; // 返回默认图标
  }

  // 如果 filePath 是空字符串，直接返回默认图标
  if (filePath.trim() === "") {
    // console.warn("filePath is an empty string:", filePath);
    return Files; // 返回默认图标
  }

  // 提取文件名
  const fileName = filePath.split(/[\\/]/).pop()?.split("?")[0]; // 去除路径和URL参数

  // 定义文件名到图标的映射
  const iconMap = {
    "image.png": Picture,
    "photo.jpg": Picture,
    "document.doc": Document,
    "report.pdf": Files,
    "video.mp4": VideoPlay,
    "presentation.ppt": VideoPlay,
    "spreadsheet.xls": Document,
    "data.xlsx": Document,
    "script.js": VideoPlay,
    "style.css": VideoPlay,
    "notes.txt": VideoPlay,
    unknown: Files, // 默认图标
  };

  // 返回对应的图标，如果没有匹配到，返回默认图标
  return iconMap[fileName.toLowerCase()] || Files;
};

// 处理预览
const handlePreview = (file) => {
  console.log(file, "filefilefilefile");
  const fileUrl = `${props.baseUrl}${file.file || file.name}`;
  const ext =
    file.file?.split(".").pop()?.toLowerCase() ||
    file.name?.split(".").pop()?.toLowerCase();

  // 直接使用 window.open 打开文件
  window.open(fileUrl, "_blank");
};

// 处理删除
const handleDelete = async (index) => {
  try {
    await ElMessageBox.confirm("确定要删除该文件吗？", "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const newList = [...normalizedEmployeeResignFileVoList.value];
    const [deletedFile] = newList.splice(index, 1);
    " emitupdate:employeeResignFileVoList", newList;
    emit("delete", deletedFile);

    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败：" + error.message);
    }
  }
};

// ,http
// 计算属性，将 employeeResignFileVoList 转换为数组
// const normalizedEmployeeResignFileVoList = computed(() => {
//   if (Array.isArray(props.employeeResignFileVoList)) {
//     isNotArray.value = false;
//     return props.employeeResignFileVoList;
//   } else {
//     isNotArray.value = true;
//     return [props.employeeResignFileVoList];
//   }
// });

const normalizedEmployeeResignFileVoList = computed(() => {
  // 1. 处理数组类型直接返回
  if (Array.isArray(props.employeeResignFileVoList)) {
    isNotArray.value = false;
    return props.employeeResignFileVoList;
  }

  // 2. 处理包含",http"的字符串（多个URL情况）
  if (
    typeof props.employeeResignFileVoList === "string" &&
    props.employeeResignFileVoList.includes(",http")
  ) {
    isNotArray.value = false;
    return props.employeeResignFileVoList
      .split(",")
      .map((file) => file.trim())
      .filter((file) => file.startsWith("http"))
      .map((file) => ({ file })); // 转换为对象数组格式
  }

  // 3. 处理JSON数组字符串
  if (
    typeof props.employeeResignFileVoList === "string" &&
    props.employeeResignFileVoList.trim().startsWith("[")
  ) {
    try {
      const parsed = JSON.parse(props.employeeResignFileVoList);
      if (Array.isArray(parsed)) {
        isNotArray.value = false;
        return parsed;
      }
    } catch (e) {
      console.warn("JSON解析失败:", e);
    }
  }

  // 4. 其他情况包装为单元素数组
  isNotArray.value = true;
  return props.employeeResignFileVoList
    ? [
        typeof props.employeeResignFileVoList === "object"
          ? props.employeeResignFileVoList
          : { url: props.employeeResignFileVoList },
      ]
    : [];
});
</script>

<style scoped></style>
